/*
 * @Description: 流程管理reducer
 * @Author: Rfan
 * @Date: 2022-12-11 11:38:43
 * @LastEditTime: 2022-12-11 16:48:00
 */

import { delItemByIdArray, editItemById, insertItem } from '@/utils/list';
import {
  DELETE_FLOW_ITEM,
  ADD_FLOW_ITEM,
  SET_FLOW_LIST,
  SET_SELECTED_ITEM,
  EDIT_FLOW_ITEM,
  SET_PROCESS_TYPE
} from '../constants';
import { treeToArr } from '@/utils';
import type { IInitialState } from '../contexts/FlowMgtContext';

interface IReducerActions {
  type: string;
  [K: string]: any;
}

export const FlowMgtReducer = (state: IInitialState, action: IReducerActions): IInitialState => {
  switch (action.type) {
    /**
     * @description: 保存表格选中的条目id
     * @param {number[]} data
     */
    case SET_SELECTED_ITEM:
      return { ...state, selectItems: action.data };

    /**
     * @description: 设置回收站条目
     */
    case SET_FLOW_LIST:
      return {
        ...state,
        list: action.data
      };

    /**
     * @description: 恢复成功删除对应条目
     */
    case ADD_FLOW_ITEM:
      return {
        ...state,
        list: insertItem(action.data, state.list)
      };

    /**
     * @description: 恢复成功删除对应条目
     */
    case EDIT_FLOW_ITEM:
      return {
        ...state,
        list: editItemById(action.id, action.data, state.list)
      };

    /**
     * @description: 删除回收站条目
     */
    case DELETE_FLOW_ITEM:
      return {
        ...state,
        list: delItemByIdArray(action.ids, state.list)
      };

    /**
     * @description: 设置流程类型列表
     */
    case SET_PROCESS_TYPE:
      return {
        ...state,
        processTypeList: action.data,
        processTypeFlatList: treeToArr(action.data)
      };

    default:
      console.log('untouched', action);
      return state;
  }
};
